package com.neoCalf.neoCommon.utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;


/**
 * @author 小牛
 * @version 1.0
 * @description TODO
 * @date 2025/4/15 0:40
 */
public class DBUtils {
    private final static DataSource dataSource;
    //创建核心类:QueryRunner:
    private final static QueryRunner queryRunner;

    static {
        dataSource = JDBC.getDataSource();
        queryRunner = new QueryRunner(dataSource);
    }

    public static <T> List<T> selectList(String sql, Object[] objects, Class<T> tClass) throws SQLException {
        return queryRunner.query(sql, objects, new BeanListHandler<>(tClass));
    }

    public static <T> T selectOne(String sql, Object[] objects, Class<T> tClass) throws SQLException {
        List<T> list = selectList(sql, objects, tClass);
        if (list != null && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    public static int update(String sql, Object[] objects) throws SQLException {
        return queryRunner.update(sql, objects);
    }
}
